package com.wendyxie.sproutup.view.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.wendyxie.sproutup.R
import com.wendyxie.sproutup.databinding.ItemChangeSkinBinding
import com.wendyxie.sproutup.db.SQLInitHelper
import com.wendyxie.sproutup.db.SQLUserDomainHelper
import com.wendyxie.sproutup.db.SQLUserHelper
import com.wendyxie.sproutup.db.SQLUserTreeHelper
import com.wendyxie.sproutup.entity.TreeEntity
import com.wendyxie.sproutup.entity.UserTreeEntity
import com.wendyxie.sproutup.utils.SPUtil

// GridView 树皮兑换
class ChangeSkinAdapter : BaseAdapter() {

    var treeList = mutableListOf<TreeEntity>()
    private lateinit var binding: ItemChangeSkinBinding

    inner class ViewHolder(private val binding: ItemChangeSkinBinding, private val adapter: ChangeSkinAdapter) :
        RecyclerView.ViewHolder(binding.root) {

        private fun showTreeImage(tree: TreeEntity) {
            if (tree.treeImageUrl.startsWith("http")) {
                binding.ivTree.setImageResource(R.drawable.ic_launcher_foreground)
            } else if (tree.treeImageUrl.startsWith("R.mipmap")) {
                val resId = binding.root.context.resources.getIdentifier(
                    tree.treeImageUrl.replace("R.mipmap.", ""),
                    "mipmap",
                    binding.root.context.packageName
                )
                Log.d(
                    "ChangeSkinAdapter",
                    "tree.treeImageUrl: ${tree.treeImageUrl}, resId: $resId, packageName=${binding.root.context.packageName}"
                )
                if (resId == 0) {
                    binding.ivTree.setImageResource(R.drawable.ic_launcher_foreground)
                } else {
                    binding.ivTree.setImageResource(resId)
                }
            } else {
                binding.ivTree.setImageResource(R.drawable.ic_launcher_background)
            }
        }

        fun bind(tree: TreeEntity) {
            // 显示树图片
            showTreeImage(tree)
            // 显示树价格
            binding.tvPrice.text = tree.treePrice.toString() + " g"
            val userId = SPUtil.getUserId(binding.root.context)
            val babyId = SPUtil.getBabyId(binding.root.context)
            val userEntity = SQLUserHelper.queryBabyById(userId, SQLInitHelper(binding.root.context).openDatabase())
            // 按钮：更换，树
            binding.btnChange.setOnClickListener {
                // 修改树表
                val userEntity = SQLUserHelper.queryBabyById(userId, SQLInitHelper(binding.root.context).openDatabase())
                userEntity.selectedTreeId = tree.treeId
                userEntity.selectedTreeSkinUrl = tree.treeImageUrl
                SQLUserHelper.updateUserById(userEntity, SQLInitHelper(binding.root.context).openDatabase())
                // 3. 刷新Adapter
                adapter.notifyDataSetChanged()
            }
            // 按钮：兑换，树
            binding.btnPurchase.setOnClickListener {
                // 1. 检查：用户积分是否足够
                val userEntity = SQLUserHelper.queryBabyById(babyId, SQLInitHelper(binding.root.context).openDatabase())
                if (userEntity.currentTotalScore < tree.treePrice) {
                    Toast.makeText(binding.root.context, "能量不足", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                // 2. 添加兑换记录
                SQLUserDomainHelper.exchangeTree(tree, userId, babyId, SQLInitHelper(binding.root.context).openDatabase())
                // 3. 刷新Adapter
                adapter.notifyDataSetChanged()
            }
            // 显示按钮：“兑换”和“更换”按钮的显示
            val userTreeList = SQLUserTreeHelper.queryUserTreesByBabyId(
                babyId,
                SQLInitHelper(binding.root.context).openDatabase()
            )
            binding.btnChange.visibility = View.GONE
            binding.btnPurchase.visibility = View.VISIBLE
            if (userTreeList.isNotEmpty()) {
                val userTree = userTreeList.find { it.treeId == tree.treeId }
                if (userTree != null) {
                    binding.btnChange.visibility = View.VISIBLE
                    binding.btnPurchase.visibility = View.GONE
                }
            }
            // 显示：树是否被选中
            if (tree.treeId == userEntity.selectedTreeId) {
                binding.vSelectedBackground.visibility = View.VISIBLE
                binding.btnChange.isEnabled = false // 为防止按钮点击事件被替换掉，需将显示放到底部
            } else {
                binding.vSelectedBackground.visibility = View.GONE
            }
            // 按钮：兑换
            Log.d("ChangeSkinAdapter", "tree.treePrice: ${tree.treePrice}, userEntity.currentTotalScore: ${userEntity.currentTotalScore}")
            binding.btnPurchase.isEnabled = tree.treePrice <= userEntity.currentTotalScore
        }
    }

    fun setItems(items: List<TreeEntity>) {
        treeList.clear()
        treeList.addAll(items)
        notifyDataSetChanged()
    }

    fun addItems(items: List<TreeEntity>) {
        treeList.addAll(items)
        notifyDataSetChanged()
    }

    override fun getCount(): Int {
        return treeList.size
    }

    override fun getItem(p0: Int): Any {
        return treeList[p0]
    }

    override fun getItemId(p0: Int): Long {
        return p0.toLong()
    }

    override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
        val layoutInflater = LayoutInflater.from(p2!!.context)
        binding = ItemChangeSkinBinding.inflate(layoutInflater)
        val viewHolder = ViewHolder(binding, this)
        viewHolder.bind(treeList[p0])
        return binding.root
    }

}
